import { constantRoutes } from '@/router'
import { menu } from '@/api/menu'
const _import = require('@/router/import/' + process.env.NODE_ENV) // 获取组件的方法
import Layout from '@/layout' // Layout 架构组件，需单独引入

export const formatRoutes = (data) => {
  var _routes = []
  for (let i = 0; i < data.length; i++) {
    var { path, component, name, meta, children } = data[i]
    if (children && children instanceof Array) {
      children = formatRoutes(children)
    }
    var route = {
      path,
      name,
      meta: {
        title: name,
        icon: meta.iconCls
      },
      component: component === 'layout' ? Layout : _import(component),
      children
    }
    _routes.push(route)
  }
  return _routes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
  }
}

const actions = {
  generateRoutes({ commit }) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async(resolve) => {
      var accessedRoutes = []
      await menu().then(async res => {
        var _accessedRoutes = await formatRoutes(res)
        commit('SET_ROUTES', _accessedRoutes)
        accessedRoutes = _accessedRoutes
      })
      resolve(accessedRoutes)
    })
  },
  resetRoutes({ commit }) {
    commit('RESET_ROUTES')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
